package realQuestion.baidu.review9_4;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;

public class JiaoTiq {
    private volatile int NUM_COUNT = 0;
    private final Lock lock = new ReentrantLock(true);
    private volatile String CODE = "A";
    private final Condition conditionA = lock.newCondition();
    private final Condition conditionB = lock.newCondition();


    private void a_Print() {
        //TODO:2023/9/4  竟然忘记释放锁了   没有释放锁也能交替打印 只是程序不会自动结束
        lock.lock();
        try {
            while (!CODE.equals("A")) {
                conditionA.await();
            }
            if (++NUM_COUNT <= 10) {
                CODE = "B";
                System.out.println(Thread.currentThread().getName() + "打印A:" + NUM_COUNT);
                conditionB.signalAll();
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }


    private void b_Print() {
        lock.lock();
        try {
            while (!CODE.equals("B")) {
                conditionB.await();
            }
            if (++NUM_COUNT <= 10) {
                CODE = "A";
                System.out.println(Thread.currentThread().getName() + "打印B:" + NUM_COUNT);
                conditionA.signalAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    public static void main(String[] args) {

        JiaoTiq jiaoTi = new JiaoTiq();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                jiaoTi.a_Print();
            }

        }, "线程A").start();


        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                jiaoTi.b_Print();
            }

        }, "线程B").start();


    }


}
